import wepy from 'wepy';
import api from "../api/api"

export default class user extends wepy.mixin {
  data = {
    userInfo: {},
    genderType:['男','女']
  };

  methods = {
    changeHead () {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
        this.uploadFile(res.tempFilePaths[0])
      }
    })
    },
  }

  async uploadFile(url){
    let res = await api.uploadFile(url)
    console.log(res)
    var obj = JSON.parse(res.data)
    this.userInfo.portrait = obj.path
    this.updateUser()
  }

  async getUserInfo() {
    let userInfo = await wepy.getStorageSync('userInfo');
    console.log(userInfo)
    if(userInfo){
      wepy.$instance.globalData.userInfo = userInfo
      this.userInfo = userInfo
    }else{
      let user = await api.userInfo()
      wepy.$instance.globalData.userInfo = user.data.data
      this.userInfo = wepy.$instance.globalData.userInfo
      await wepy.setStorageSync('userInfo', user.data.data)
    }
    this.$apply()
  }

  async updateUser() {
    await api.updateUserInfo({
      method:'POST',
      query:this.userInfo
    })
    let user = await api.userInfo()
    wepy.$instance.globalData.userInfo = user.data.data
    this.userInfo = wepy.$instance.globalData.userInfo
    await wepy.setStorageSync('userInfo', user.data.data)
    this.$apply()
  }

  onLoad () {
  }
}
